import * as $apis from '@/api/'
import { GD_S_KEY, GD_WX_KEY } from '@/api/config.js'
import $amap from '@/common/amap-wx/amap-wx.js'
import $mUtils from '@/common/utils'
import { defineStore } from 'pinia'

interface Tabbar {
	iconPath: string
	selectedIconPath: string
	pagePath: string
	text: string
}

export const state = defineStore('state', {
	// 开启后对 state 的数据读写都将持久化
	unistorage: true,
	// Store
	state: () => {
		return {
			versionInfo: {
				versionSwitch: 0, // 是否上线前功能隐藏,默认关闭
				open_debug: 0, // 是否Debug模式,默认关闭
				is_grey: 0 // 是否置灰模式,默认关闭
			},
			tabbar: [] as Tabbar[], // TABBAR
			showProgress: false // 进度条
		}
	},
	// Getters
	getters: {
		versionSwitch(): number {
			return this.versionInfo.versionSwitch
		}
	},
	// Actions
	actions: {
		// 更新TABBAR
		updateTabbar(versionSwitch = 0) {
			let tabbar: Tabbar[] = [
				{
					iconPath: '/static/icon-home.png',
					selectedIconPath: '/static/icon-home-active.png',
					pagePath: '/pages/index/index',
					text: '首页'
				},
				{
					iconPath: '/static/icon-mine.png',
					selectedIconPath: '/static/icon-mine-active.png',
					pagePath: '/pages/index/mine',
					text: '我的'
				}
			]
			// 版本控制入口
			if (versionSwitch) {
				tabbar = tabbar.filter(item => ![].includes(item.text as never))
			}
			this.tabbar = tabbar
		},
		// 进度条开关
		progress(data: any) {
			this.showProgress = data
		},
		// 获取版本号,功能开关
		getVersionInfo(version: string) {
			let type: string = $mUtils.isIOSPlatform() ? 'ios' : 'android'
			// #ifdef MP-WEIXIN
			type = 'mp-weixin'
			// #endif
			// #ifdef H5
			type = 'h5'
			// #endif
			return new Promise(resolve => {
				$apis
					.getVersionInfo({
						version,
						type
					})
					.then((res: any) => {
						if (res.code == 0) {
							const data = res.data || {}
							// 更新TABBAR
							this.updateTabbar(data.switch)
							this.versionInfo.is_grey = data.is_grey
							this.versionInfo.open_debug = data.open_debug
							this.versionInfo.versionSwitch = data.switch || 0

							if (import.meta.env.MODE === 'production' && !data.open_debug) {
								console.log = () => ({}) // 全局console 关闭
							}
						}
						resolve(res)
					})
			})
		},
		// 当前定位
		GetCurrentPos(goIp = true) {
			return new Promise(resolve => {
				// #ifdef H5
				this.realTimeLocation((res: any) => {
					resolve(res)
				})
				// #endif
				// #ifndef H5
				let myAmapFun = new $amap({
					key: GD_WX_KEY
				})
				// 自动定位
				myAmapFun.getRegeo({
					success(data: any) {
						if (data.length) {
							resolve(data[0])
						}
					},
					fail: () => {
						// 自动调用ip定位
						if (goIp) {
							this.realTimeLocation((res: any) => {
								resolve(res)
							})
						} else {
							resolve(null)
						}
					}
				})
				// #endif
			})
		},
		// ip定位(不用授权)
		realTimeLocation(callback: any) {
			return new Promise(resolve => {
				wx.request({
					url: `https://restapi.amap.com/v3/ip?key=${GD_S_KEY}`,
					header: {
						'content-type': 'application/json'
					},
					success(res: any) {
						// 所在城市范围的左下右上对标对
						let { rectangle, city, province } = res.data
						rectangle = rectangle.split(';')[0].split(',')
						let oData = {
							longitude: Number(rectangle[0]),
							latitude: Number(rectangle[1]),
							name: `${province},${city}`,
							regeocodeData: {
								addressComponent: {
									city,
									province
								}
							}
						}
						uni.setStorageSync('userLocation', `${rectangle[0]},${rectangle[1]}`)
						resolve(oData)
						if (callback) {
							callback(oData)
						}
					}
				})
			})
		},
		// 全国市区/县转经纬
		getLngLat(data: any) {
			return new Promise(resolve => {
				let params: any = {}
				if (typeof data === 'string') {
					params = {
						output: 'JSON',
						address: data,
						key: GD_S_KEY
					}
				} else {
					params = {
						...data
					}
					params.output = 'JSON'
					params.key = GD_S_KEY
				}

				wx.request({
					url: `https://restapi.amap.com/v3/geocode/geo?output=${params.output}&address=${params.address}&key=${params.key}`,
					header: {
						'content-type': 'application/json'
					},
					success(res: any) {
						const { infocode, geocodes } = res.data
						if (infocode === '10000') {
							resolve({
								...geocodes[0],
								longitude: geocodes[0].location.split(',')[0],
								latitude: geocodes[0].location.split(',')[1]
							})
						} else {
							$mUtils.tip('请传入正确的地址')
						}
					}
				})
			})
		}
	}
})
